package com.wlyuan.open.scanner.application.factory;

import com.wlyuan.open.scanner.application.annotation.ScannerCode;
import com.wlyuan.open.scanner.application.handler.full.BaseScannerHandler;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lijing
 * @description
 */
public final class ScannerHandlerFactory {

    /**
     * 全量同步实现类map
     */
    private static Map<String, BaseScannerHandler> handlersMap = new ConcurrentHashMap<>();

    public static BaseScannerHandler getHandler(String scannerCode) {
        return handlersMap.get(scannerCode);
    }

    public static synchronized void initHandlers(Collection<BaseScannerHandler> handlers) {
        Optional.ofNullable(handlers).ifPresent(
                hs -> {
                    hs.forEach(h -> {
                        Optional.ofNullable(h.getClass().getAnnotation(ScannerCode.class)).ifPresent(an -> {

                            String code = an.code().getVal();

                            handlersMap.put(code, h);

                        });
                    });
                }
        );
    }

}
